import React, { useEffect, useRef, useState } from "react";
import { Modal } from "../Modal/Modal";
import {
    AIConfig as AIConfigType,
    ModelList,
} from "../../../core/types/ollama";
import { ConfigService } from "../../../core/services/config_service";
import { ErrorIcon } from "../icons/ErrorIcon";
import { QuestionIcon } from "../icons/QuestionIcon";
import { Input, Select, Button, CircleButton } from "../components/form";
import styles from "./AIConfigModal.module.css";
import { useModelInfo } from "../../store/useModelInfo";
import { useAIConfig } from "../../store/useAIConfig";
import { useModal } from "../../store/useModal";

export const AIConfigModal: React.FC = () => {
    const openModelInfoModal = useModelInfo((state) => state.open);
    const isOpen = useAIConfig((state) => state.isOpen);
    const toggle = useAIConfig((state) => state.toggle);

    const [config, setConfig] = useState<AIConfigType>({
        provider: "",
        baseUrl: "",
        selectedModel: "",
    });
    const [models, setModels] = useState<ModelList>([]);
    const loadingModelList = useRef(false);
    const [error, setError] = useState<string | null>(null);
    const [saving, setSaving] = useState(false);

    const configService = ConfigService.getInstance();

    const handleModelInfoClick = () => {
        openModelInfoModal(config.selectedModel);
    };

    const loadModels = async () => {
        loadingModelList.current = true;
        setError(null);
        try {
            const modelList = await configService.getModels();
            setModels(modelList);
        } catch (err) {
            setError("无法加载模型列表，请检查服务地址是否正确");
            console.error("Failed to load models:", err);
        } finally {
            loadingModelList.current = false;
        }
    };

    const handleBaseUrlChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const newBaseUrl = e.target.value;
        setConfig((prev) => ({ ...prev, baseUrl: newBaseUrl }));
    };

    const handleBaseUrlBlur = () => {};

    const handleSave = async () => {
        setSaving(true);
        try {
            await configService.saveConfig(config);
            setError(null);
            // 显示成功提示
            useModal.getState().alert("配置已保存");
        } catch (err) {
            setError("保存配置失败");
            console.error("Failed to save config:", err);
        } finally {
            setSaving(false);
            toggle();
        }
    };

    // 初始化配置选项
    useEffect(() => {
        (async function () {
            if (loadingModelList.current) return;
            // 加载模型列表
            await loadModels();
            // 加载保存的配置
            const savedConfig = configService.getConfig();
            setConfig(savedConfig);
        })();
    }, []);
    return (
        <Modal isOpen={isOpen} title="AI配置" onClose={toggle}>
            <div className={styles.formSection}>
                <Select
                    label="服务商(当前仅支持Ollama)"
                    className={styles.select}
                    value={config.provider}
                    disabled
                    options={[{ value: "ollama", label: "Ollama" }]}
                />

                <Input
                    label="服务地址"
                    value={config.baseUrl}
                    onChange={handleBaseUrlChange}
                    onBlur={handleBaseUrlBlur}
                    placeholder="http://localhost:11434"
                />

                <Select
                    label="模型"
                    value={config.selectedModel}
                    onChange={(value) => {
                        setConfig((prev) => ({
                            ...prev,
                            selectedModel: value,
                        }));
                    }}
                    disabled={loadingModelList.current}
                    options={[
                        { value: "", label: "请选择模型" },
                        ...models.map((model) => ({
                            value: model.name,
                            label: model.name,
                        })),
                    ]}
                    loading={loadingModelList.current}
                    actionButton={
                        <CircleButton
                            size="small"
                            onClick={handleModelInfoClick}
                            disabled={
                                !config.selectedModel ||
                                loadingModelList.current
                            }
                            title="查看模型信息"
                        >
                            <QuestionIcon size={16} color="currentColor" />
                        </CircleButton>
                    }
                />

                {error && (
                    <div className={styles.error}>
                        <ErrorIcon size={20} color="currentColor" />
                        <span>{error}</span>
                    </div>
                )}

                <Button
                    className={styles.button}
                    onClick={handleSave}
                    disabled={
                        loadingModelList.current ||
                        saving ||
                        !config.baseUrl ||
                        !config.selectedModel
                    }
                    variant="primary"
                    loading={saving}
                    loadingText="保存中..."
                >
                    保存配置
                </Button>
            </div>
        </Modal>
    );
};
